﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Services;
using Jackie.Update.Entities;
using Jackie.Utility;

namespace Skomart.Update.Service
{
    /// <summary>
    /// 文件下载服务
    /// </summary>
    [WebService(Namespace = "http://service.skomart.net/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class DownloadService : System.Web.Services.WebService
    {
        /// <summary>
        /// 获取系统的更新配置
        /// </summary>
        /// <param name="systemName">系统名称</param>
        /// <returns></returns>
        [WebMethod]
        public SystemConfigInfo GetUpdateConfig(string systemName)
        {
            var configurationManager = new UpdateConfigurationManager();
            return configurationManager[systemName];
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="system">系统名称</param>
        /// <param name="file">文件</param>
        /// <param name="offset">文件偏移量</param>
        /// <returns></returns>
        [WebMethod]
        public byte[] GetFileByte(string system, string file, long offset)
        {
            try
            {
                var updateFilesPath =
                    Path.Combine(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath),
                                 ConfigurationManager.AppSettings["UpdateFileFolder"]);
                var serverSystemPath = Path.Combine(updateFilesPath, system);
                var updateFilePath = Path.Combine(serverSystemPath, file);
                if (!File.Exists(updateFilePath))
                    throw new FileNotFoundException("file not found!", updateFilePath);
                var length = JackieConvert.ToInt(ConfigurationManager.AppSettings["ReadMaxLength"]);
                var buffer = new byte[length];
                using (var fileStream = new FileStream(updateFilePath, FileMode.Open, FileAccess.Read))
                {
                    fileStream.Seek(offset, SeekOrigin.Begin);
                    fileStream.Read(buffer,0, length);
                }
                return buffer;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
